package com.cucn.msmservice.controller;

import com.cucn.commonutils.Result;
import com.cucn.msmservice.service.MsmService;
import com.cucn.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author KouChaoJie
 * @since: 2021/10/9 22:02
 */
@RestController
//@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送短信的方法
     *
     * @param phone 手机号
     */
    @GetMapping("/send/{phone}")
    public Result sendMsm(@PathVariable String phone) {
        //从redis里获取验证码,如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }

        //如果redis获取不到,进行腾讯云发送
        //生成4位随机值,传递给腾讯云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param, phone);

        if (isSend) {
            //发送成功,把发送成功的验证码放到redis里
            //设置有效时间
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.error().message("验证码发送失败!");
        }
    }
}
